const fs = require('fs')
const out = process.stdout
const filePath = 'photoshop.zip'

// 创建可读流
const readStream = fs.createReadStream(filePath)
// 创建可写流
const writeStream = fs.createWriteStream('photoshop.copy.zip')

// 读取文件信息
const stat = fs.statSync(filePath)

// 文件大小，单位字节
let totalSize = stat.size
// 处理过的数据大小，单位字节
let passedLength = 0
// 处理过的数据的大小，单位MB
let lastSize = 0
// 开始处理时间
let startTime = Date.now()

// 可读流绑定'data'事件
readStream.on('data', (chunk) => {
  passedLength += chunk.length
  // 防爆仓处理
  if (writeStream.write(chunk) === false) {
    readStream.pause()
  }
})

// 文件读完了,关闭可写流
readStream.on('end', () => {
  writeStream.end()
})

// 触发'drain'事件了，继续读取
writeStream.on('drain', () => {
  readStream.resume()
})

// 循环显示
setTimeout(function show () {
  // 已经处理数据的百分比
  let percent = Math.ceil(passedLength / totalSize * 100)
  // 已经处理数据的大小,单位MB
  let size = Math.ceil(passedLength / 1000000)
  // 当前处理数据的大小
  let diff = size - lastSize
  // 重新给lastSize赋值
  lastSize = size
  // 清空输出信息
  out.clearLine()
  out.cursorTo(0)
  // 输出信息
  out.write('已完成' + size + 'MB， ' + percent + '%，速度：' + diff * 2 + 'MB/s')
  if (passedLength < totalSize) {
    setTimeout(show, 500)
  } else {
    let endTime = Date.now()
    console.log()
    console.log('共用时：' + (endTime - startTime) / 1000 + '秒。')
  }
}, 500)
